package csc.traning.wpsj.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.traning.wpsj.dao.User;

/**
 * Servlet implementation class CreateFolderServlet
 */
public class CreateFolderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateFolderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter pr = response.getWriter();
		
		HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){
                throw new ServletException("Required to login");
        }	
		
		String name = request.getParameter("name");
		
		String currentFolder = request.getParameter("currentFolder");
		
		String currentFolderPath = new StringBuffer("users/").append(user.getUserName()).append("/upload-folder").toString();
		if(currentFolder != null && !("").equals(currentFolder)){
        	 //String[] folers =  currentFolder.split("_");
             //for (String folder : folers) {
            	 currentFolderPath = new StringBuffer(currentFolderPath).append("/").append(currentFolder).toString();
             //}
        }
		
		String realNewFolderPath = getServletContext().getRealPath(new StringBuffer(currentFolderPath).append("/").append(name).toString());
		File file = new File(realNewFolderPath);
		if(file.mkdirs()){
			pr.print(1);
		}else{
			pr.print(-1);
		}
		
		
	}

}
